# -*- coding: utf-8 -*-
# @Time    : 2019-01-16 16:57
# @Author  : jerry
# @FileName: sys_models.py
# @Software: PyCharm Professional Edition
# @Version : python 3.6.2
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)

from master import db, app
from datetime import datetime
from passlib.hash import pbkdf2_sha256


class User(db.Model):
    """用户实体"""
    __tablename__ = 'TB_SYS_USER'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    id = db.Column(db.Integer, '序号', primary_key=True, autoincrement=True)
    name = db.Column(db.String(32), '账户名', unique=True, nullable=False)
    real_name = db.Column(db.String(32), doc='真实姓名', nullable=False)
    password = db.Column(db.String(32), doc='账户密码', nullable=False)
    salt = db.Column(db.SMALLINT, doc='加密盐')
    email = db.Column(db.String(64), doc='电邮地址')
    phone_num = db.Column(db.String(11), doc='手机号')
    creatime = db.Column(db.TIMESTAMP, default=datetime.now(), server_default=db.text("CURRENT_TIMESTAMP"), doc='创建时间',
                         nullable=False)
    deleted = db.Column(db.Boolean, default=False, doc='逻辑删除位 1:deleted 0:no_deleted', nullable=False)
    group_id = db.Column(db.Integer, db.ForeignKey('TB_SYS_GROUP.id'))

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)

    def __repr__(self):
        return "User<name:%r>" % self.name

    def get_json(self):
        user_json = {
            'id': self.id,
            'name': self.name,
            'real_name': self.real_name,
            'email': self.email,
            'phone': self.phone_num,
            'group': self.group_id
        }
        return user_json

    def hash_password(self, password):
        """
        SHA-256加密用户密文

        :param password: 用户输入的明码
        :return: 无
        """
        self.password = pbkdf2_sha256.hash(password)

    def verify_password(self, password):
        """
        验证用户密文

        :param password:
        :return:
        """
        return pbkdf2_sha256.verify(password, self.password)

    def generate_auth_token(self, expiration=1800):
        """
        生成token

        :param expiration: token过期时长（秒）
        :return:
        """
        token_generator = Serializer(secret_key=app.config['SECRET_KEY'],
                                     salt=app.config['AUTH_SALT'],
                                     expires_in=expiration)
        timestamp = datetime.now()
        access_token = token_generator.dumps({'user_id': self.id,
                                              'group_id': self.group_id,
                                              'iat': timestamp})
        return access_token

    @staticmethod
    def verify_auth_token(token):
        """
        验证token

        :param token:
        :return: #to_json: {'statue': '1|2|3', 'msg': '<说明>', 'object': User|None}
        """
        s = Serializer(secret_key=app.config['SECRET_KEY'],
                       salt=app.config['AUTH_SALT'])
        try:
            data = s.load(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None
        user = User.query.get(data['user_id'])
        return user


class UserGroup(db.Model):
    """用户组实体"""
    __tablename__ = 'TB_SYS_GROUP'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    group_name = db.Column(db.String(32), unique=True, nullable=False)
    modules = db.Column(db.String(500))
    created_time = db.Column(db.TIMESTAMP, default=datetime.now())

    users = db.relationship(User, backref='group_and_users', lazy='dynamic')


class MyTest(db.Model):
    """测试表实体"""
    __tablename__ = 'TEST'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(32))
    age = db.Column(db.SmallInteger)
